//
//  CharacterViewController.m
//  us
//
//  Created by lhx on 2025/4/1.
//

#import "CharacterViewController.h"
#import "AddYourInfoViewController.h"
#import "CharacterModel.h"
 
#import "CharacterToolCollectionViewCell.h"
#import "CharacterUnitCollectionViewCell.h"
#import "CharacterToolBottomView.h"
@interface CharacterViewController ()<UICollectionViewDelegate,UICollectionViewDataSource, UIPageViewControllerDataSource, UIPageViewControllerDelegate>


@property (nonatomic, assign) USSexType characterSex;//左女  右男

@property (nonatomic, strong) NSMutableArray <CharacterModel *>*characterList;
@property (nonatomic, assign) NSInteger typeIndex;

@property (nonatomic, strong) UIPageViewController *pageViewController;
@property (nonatomic, strong) NSMutableArray<UICollectionViewController *> *pageControllers;

@property (nonatomic, strong) CharacterToolBottomView *toolBottomView;



@end

@implementation CharacterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.navigationItem.title = @"选择你们的卡通形象";
    
    [self initDefaultCharacterGroups];
    self.pageControllers = [NSMutableArray array];

    [self setUpView];
    [self setupPageView];
    

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.toolCollectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:self.typeIndex inSection:0] animated:NO scrollPosition:UICollectionViewScrollPositionNone];
        self.toolBottomView.jk_width = self.toolCollectionView.contentSize.width;
    });
    [self selectCharacter:self.typeIndex isChangeRole:YES];

    
    if (self.isEdit) {
        self.myCharacterView.character = USUser.user.character;
        self.relCharacterView.character = USUser.user.relCharacter;
    }else {
        //默认头像
        self.myCharacterView.character = [USCartoonCharacter defaultGirlCharacter];
        self.relCharacterView.character = [USCartoonCharacter defaultBoyCharacter];
    }
    
    [self selectSex:USSexTypeFemale];

    if (self.isEdit) {
        [self.nextStepBtn setTitle:@"完成" forState:0];
    }
}

#pragma mark - 下一步
- (IBAction)nextAction:(id)sender {
    NSArray *femaleArray = [CharacterUnitModel mj_keyValuesArrayWithObjectArray:self.myCharacterView.character.parts];
    NSArray *maleArray = [CharacterUnitModel mj_keyValuesArrayWithObjectArray:self.relCharacterView.character.parts];

    // 获取当前时间戳（单位：秒）
    NSTimeInterval timestamp = [[NSDate date] timeIntervalSince1970];
    NSString *time = [NSString stringWithFormat:@"%li",(NSInteger)timestamp];
 
    // 包装为一个字典，包含时间戳和原数组
    NSDictionary *payload = @{
        @"timestamp": time,
        @"parts": femaleArray ?: @[],
        @"relParts":maleArray ?:@[]
    };

    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:payload options:0 error:&error];

    NSString *jsonString = nil;
    if (!error && jsonData) {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    } else {
        NSLog(@"[Error] JSON 序列化失败: %@", error);
    }
 
    [self updateUserInfoWithParts:jsonString];
}

///修改人物
- (void)updateUserInfoWithParts:(NSString *)parts{
    [USFeedbackTool notifySuccess];

    [self startLoading];
    NSDictionary *params = @{@"parts":parts};
   
    [[EMNetWork shareManager] em_post:API_EditUser
                               params:params
                                  hud:nil
                           showError:YES
                              success:^(EMApiModel *api) {
        [self.view endEditing:YES];
        
        if (!api.success) {
            [self loadingFailed];
            return;
        }
        
//        [self loadingFailed];
        self.dataState = EmptyDataStateNone;
        [self.us_tableView reloadEmptyDataSet];
        
        USUser *user = [USUser user];
        user.parts = parts;
        [USUser saveUser:user];

        if (self.isEdit) {
            [self.navigationController popViewControllerAnimated:YES];
            
            [USIMCmdCustomManager imSendCmdWithAction:USIMCmdAction_UploadUserInfo andExt:@{}];
        }else {
            AddYourInfoViewController *vc = [[AddYourInfoViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:USNotificationCharacter object:nil];

    } fail:^{
        
        [self loadingFailed];
        
    }];
}

#pragma warnig 临时本地数据
- (void)initDefaultCharacterGroups {
    [self.characterList removeAllObjects];
        
    
    CharacterModel *eyesModel = [CharacterModel new];
    eyesModel.name = @"眼睛";
    eyesModel.icon = @"eyes";
    eyesModel.type = Character_eyes;
    NSMutableArray *eyesArr = [NSMutableArray array];
    for (int i = 0 ; i<23; i++) {
        CharacterUnitModel *model = [CharacterUnitModel new];
        model.icon = [NSString stringWithFormat:@"eyes_%i",i + 1];
        model.type = eyesModel.type;

        [eyesArr addObject:model];
    }
    eyesModel.units = eyesArr;
    

    CharacterModel *hairModel = [CharacterModel new];
    hairModel.name = @"头发";
    hairModel.icon = @"hair";
    hairModel.type = Character_hair;

    NSMutableArray *hairArr = [NSMutableArray array];
    for (int i = 0 ; i<17; i++) {
        CharacterUnitModel *model = [CharacterUnitModel new];
        model.icon = [NSString stringWithFormat:@"hair_female_%i",i + 1];
        model.type = hairModel.type;
        [hairArr addObject:model];
    }
    for (int i = 0 ; i<17; i++) {
        CharacterUnitModel *model = [CharacterUnitModel new];
        model.icon = [NSString stringWithFormat:@"hair_male_%i",i + 1];
        model.type = hairModel.type;
        [hairArr addObject:model];
    }
    hairModel.units = hairArr;
    
    
    CharacterModel *clothesModel = [CharacterModel new];
    clothesModel.name = @"衣服";
    clothesModel.icon = @"clothes";
    clothesModel.type = Character_clothes;
    NSMutableArray *clothesArr = [NSMutableArray array];
    for (int i = 0 ; i<21; i++) {
        CharacterUnitModel *model = [CharacterUnitModel new];
        model.icon = [NSString stringWithFormat:@"clothes_%i",i + 1];
        model.type = clothesModel.type;

        [clothesArr addObject:model];
    }
    clothesModel.units = clothesArr;
    
    CharacterModel *mouthModel = [CharacterModel new];
    mouthModel.name = @"嘴巴";
    mouthModel.icon = @"mouth";
    mouthModel.type = Character_mouth;
    NSMutableArray *mouthArr = [NSMutableArray array];
    for (int i = 0 ; i<25; i++) {
        CharacterUnitModel *model = [CharacterUnitModel new];
        model.icon = [NSString stringWithFormat:@"mouth_%i",i + 1];
        model.type = mouthModel.type;
        [mouthArr addObject:model];
    }
    mouthModel.units = mouthArr;
    
    CharacterModel *faceModel = [CharacterModel new];
    faceModel.name = @"脸部";
    faceModel.icon = @"face";
    faceModel.type = Character_face;
    NSMutableArray *faceArr = [NSMutableArray array];
    
    CharacterUnitModel *noFaceModel = [CharacterUnitModel new];
    noFaceModel.icon = [NSString stringWithFormat:@"character_empty"];
    noFaceModel.type = faceModel.type;
    [faceArr addObject:noFaceModel];
    
    for (int i = 0 ; i<17; i++) {
        CharacterUnitModel *model = [CharacterUnitModel new];
        model.icon = [NSString stringWithFormat:@"face_%i",i + 1];
        model.type = faceModel.type;
        [faceArr addObject:model];
    }
    faceModel.units = faceArr;
    

    CharacterModel *assetModel = [CharacterModel new];
    assetModel.name = @"饰品";
    assetModel.icon = @"accessories";
    assetModel.type = Character_asset;

    NSMutableArray *assetArr = [NSMutableArray array];
    
    CharacterUnitModel *noAssetModel = [CharacterUnitModel new];
    noAssetModel.icon = [NSString stringWithFormat:@"character_empty"];
    noAssetModel.type = assetModel.type;
    [assetArr addObject:noAssetModel];
    
    for (int i = 0 ; i<13; i++) {
        CharacterUnitModel *model = [CharacterUnitModel new];
        model.icon = [NSString stringWithFormat:@"accessories_%i",i + 1];
        model.type = assetModel.type;
        [assetArr addObject:model];
    }
    assetModel.units = assetArr;
    
    
    [self.characterList addObject:hairModel];
    [self.characterList addObject:eyesModel];
    [self.characterList addObject:mouthModel];
    [self.characterList addObject:clothesModel];
    [self.characterList addObject:faceModel];
    [self.characterList addObject:assetModel];
}

#pragma mark - 选择部位
- (void)selectCharacter:(NSInteger)index isChangeRole:(BOOL)isChangeRole{
    
    if (_typeIndex == index && !isChangeRole) {
        return;
    }
    
    self.typeIndex = index;
    
    CharacterModel *charaModel = self.characterList[index];
    
    NSInteger selectIndex = 0;
    BOOL hasSelect = false;
    
    NSArray *compareArr = @[];
    
    if (self.characterSex == USSexTypeFemale) {
        compareArr = self.myCharacterView.character.parts;
    }else if (self.characterSex == USSexTypeMale) {
        compareArr = self.relCharacterView.character.parts;
    }
    
    for (CharacterUnitModel *unitModel in compareArr) {
        if (unitModel.type == charaModel.type) {
            
            for (int i = 0; i<charaModel.units.count; i++) {
                CharacterUnitModel *model = charaModel.units[i];
                if ([model.icon isEqualToString:unitModel.icon]) {
                    selectIndex = i;
                    hasSelect = YES;
                    break;
                }
            }
        }
    }
    
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        UICollectionViewController *vc = (UICollectionViewController *)self.pageViewController.viewControllers.firstObject;

        [vc.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:selectIndex inSection:0]
                                  atScrollPosition:UICollectionViewScrollPositionNone
                                          animated:YES];
        
        [vc.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:selectIndex inSection:0] animated:NO scrollPosition:UICollectionViewScrollPositionNone];
    });
    
}
#pragma mark - 选择物件
- (void)selectUnitIndex:(NSInteger)unitIndex {
    
    [USFeedbackTool selectionChanged];
    CharacterUnitModel *unitModel = self.characterList[self.typeIndex].units[unitIndex];
    if (self.characterSex == USSexTypeFemale) {
        [self.myCharacterView changePart:unitModel];
        
    }else if (self.characterSex == USSexTypeMale) {
        
        [self.relCharacterView changePart:unitModel];
    }
}

- (void)sexViewTapped:(UITapGestureRecognizer *)gesture {
    [USFeedbackTool impactMedium];
    
    UIView *tappedView = gesture.view;
    [self selectSex:tappedView.tag - 2000];
    
}

- (void)selectSex:(USSexType)sex{
    
    self.characterSex = sex;

    if (sex == USSexTypeFemale) {
        self.myCharacterView.isSelect = YES;
        self.relCharacterView.isSelect = NO;
        self.meLab.alpha = 1;
        self.taLab.alpha = 0.6;

    }else if (sex == USSexTypeMale) {
        self.myCharacterView.isSelect = NO;
        self.relCharacterView.isSelect = YES;
        self.meLab.alpha = 0.6;
        self.taLab.alpha = 1;

    }
    
    [self selectCharacter:self.typeIndex isChangeRole:YES];

}

- (void)setUpView {
    UITapGestureRecognizer *leftTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sexViewTapped:)];
    self.myCharacterView.tag = 2000;
    [self.myCharacterView addGestureRecognizer:leftTapGesture];
    self.myCharacterView.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *rightTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sexViewTapped:)];
    self.relCharacterView.tag = 2001;
    [self.relCharacterView addGestureRecognizer:rightTapGesture];
    self.relCharacterView.userInteractionEnabled = YES;
    
    
    [self.nextStepBtn setBackgroundImage:[UIImage jk_imageWithColor:UIColor.titleColor] forState:0];
    
    [self.toolBgView addSubview:self.toolBottomView];
    self.toolBottomView.userInteractionEnabled = NO;
    self.toolBottomView.frame = CGRectMake(0, 0, self.toolBgView.jk_width, 8);

    UICollectionViewFlowLayout *toolLayout = [[UICollectionViewFlowLayout alloc]init];
    toolLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    toolLayout.itemSize = CGSizeMake(56, 38);
    toolLayout.minimumLineSpacing = 28;
    toolLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 10);
    self.toolCollectionView.collectionViewLayout = toolLayout;
    self.toolCollectionView.alwaysBounceHorizontal = YES;
    self.toolCollectionView.alwaysBounceVertical = NO;
    self.toolCollectionView.showsHorizontalScrollIndicator = NO;
    self.toolCollectionView.dataSource = self;
    self.toolCollectionView.delegate = self;
    [self.toolCollectionView registerClass:[CharacterToolCollectionViewCell class] forCellWithReuseIdentifier:@"CharacterToolCollectionViewCell"];

}

- (void)setupPageView {
    self.pageViewController = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
    self.pageViewController.dataSource = self;
    self.pageViewController.delegate = self;

    self.pageViewController.view.backgroundColor = UIColor.clearColor;
    
    
    for (NSInteger i = 0; i < self.characterList.count; i++) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        CGFloat width = (ScreenWidth - 16 * 2 - 12 * 3)/4.0;
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.itemSize = CGSizeMake(width , width);
        layout.minimumInteritemSpacing = 12;
        layout.minimumLineSpacing = 12;
        layout.sectionInset = UIEdgeInsetsMake(16, 0, 16, 0);
        UICollectionViewController *vc = [[UICollectionViewController alloc] initWithCollectionViewLayout:layout];
        vc.view.backgroundColor = UIColor.clearColor;
        vc.collectionView.backgroundColor = UIColor.clearColor;
        vc.collectionView.delegate = self;
        vc.collectionView.dataSource = self;
        vc.collectionView.tag = i;
        [vc.collectionView registerClass:[CharacterUnitCollectionViewCell class] forCellWithReuseIdentifier:@"CharacterUnitCollectionViewCell"];
        [self.pageControllers addObject:vc];
    }

    if (self.pageControllers.count > 0) {
        [self.pageViewController setViewControllers:@[self.pageControllers[0]] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    }

    [self.pageBackView addSubview:self.pageViewController.view];
    self.pageViewController.view.translatesAutoresizingMaskIntoConstraints = NO;
    [self.pageViewController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.pageBackView);
    }];

}


- (CharacterToolBottomView *)toolBottomView {
    if (_toolBottomView == nil) {
        _toolBottomView = [[CharacterToolBottomView alloc]init];
    }
    return _toolBottomView;
}

- (NSMutableArray <CharacterModel *>*)characterList {
   if(_characterList == nil) {
       _characterList = [NSMutableArray array];
   }
   return _characterList;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.toolCollectionView) {
        self.toolBottomView.jk_left =  - scrollView.contentOffset.x;
    }
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(nonnull UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (collectionView == self.toolCollectionView) {
        return self.characterList.count;
    }else {
        return self.characterList[collectionView.tag].units.count;
    }
}

- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return YES;
    
}


- (nonnull __kindof UICollectionViewCell *)collectionView:(nonnull UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    if (collectionView == self.toolCollectionView) {
        
        CharacterToolCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CharacterToolCollectionViewCell" forIndexPath:indexPath];
        
        CharacterModel *model = self.characterList[indexPath.row];
        cell.nameLab.text = model.name;
        cell.imgView.image = [UIImage imageNamed:model.icon];
        
         return cell;
    }else{
        
        
        CharacterUnitCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CharacterUnitCollectionViewCell" forIndexPath:indexPath];
         
        CharacterModel *model = self.characterList[collectionView.tag];
        CharacterUnitModel *unitMode = model.units[indexPath.row];
        cell.imgView.image = [UIImage imageNamed:unitMode.icon];
        
        return cell;
    }
    
}
 

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [USFeedbackTool selectionChanged];
    
    if (collectionView == self.toolCollectionView) {
        NSInteger newIndex = indexPath.item;
        UIPageViewControllerNavigationDirection direction = newIndex > self.typeIndex ? UIPageViewControllerNavigationDirectionForward : UIPageViewControllerNavigationDirectionReverse;
        
        @weakify(self)
        [self.pageViewController setViewControllers:@[self.pageControllers[newIndex]] direction:direction animated:YES completion:^(BOOL finished) {
            @strongify(self)
            if (finished) {
                [self selectCharacter:indexPath.row isChangeRole:NO];
            }
        }];
        

        [collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
        
        UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
        [self.toolBottomView.selectImgView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.toolBottomView).offset(cell.frame.origin.x);
        }];
        
        [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            [self.view layoutIfNeeded];
        } completion:nil];
    
        
    }else {
        
        [self selectUnitIndex:indexPath.row];
        
    }
}

#pragma mark - UIPageViewController Delegate/DataSource

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    NSInteger index = [self.pageControllers indexOfObject:(UICollectionViewController *)viewController];
    return index > 0 ? self.pageControllers[index - 1] : nil;
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    NSInteger index = [self.pageControllers indexOfObject:(UICollectionViewController *)viewController];
    return index < self.pageControllers.count - 1 ? self.pageControllers[index + 1] : nil;
}

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed {
    if (completed) {
        [USFeedbackTool selectionChanged];

        UICollectionViewController *vc = (UICollectionViewController *)pageViewController.viewControllers.firstObject;
        self.typeIndex = vc.collectionView.tag;
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.typeIndex inSection:0];
        [self.toolCollectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionCenteredHorizontally];
        
        UICollectionViewCell *cell = [self.toolCollectionView cellForItemAtIndexPath:indexPath];
        [self.toolBottomView.selectImgView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.toolBottomView).offset(cell.frame.origin.x);
        }];
        
        [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            [self.view layoutIfNeeded];
        } completion:nil];
        
        [self selectCharacter:self.typeIndex isChangeRole:YES];
    }
}
@end
